/*
 * @Description: 散文件与档案类型弹窗内容
 * @Author: Zzt
 * @Date: 2022-11-03 16:44:28
 * @LastEditTime: 2023-01-30 17:57:42
 */
import { Button, Form, Select, Space, Table } from 'antd';
import classNames from 'classnames/bind';
import { observer } from 'mobx-react-lite';
import { indexToTitle, jsonClone } from '@/utils';
import { v4 as uuidv4 } from 'uuid';
import { delItemById } from '@/utils/list';
import { memo, useEffect, useState } from 'react';
import { fetchFondsListByUnitId } from '@/api/fonds';
import styles from '../../../styles/form.module.scss';
import Column from 'antd/es/table/Column';
import { IArchiveType, ILevel } from '@/interfaces/archiveType';
import { IFond } from '@/interfaces/fond';
import { fetchATListByFondId } from '@/api/archivesType';
import { searchFetchFields } from '@/api/metadata';

const cx = classNames.bind(styles);
const { Option } = Select;
class ExcelItem {
  key: string;

  fieldName: string = null;

  typeTitle: string = null;

  title: string = null;

  constructor(idx: number) {
    this.key = uuidv4();
  }
}

const relationship = [
  { id: 1, value: '等于' },
  { id: 2, value: '包含' },
  { id: 3, value: '属于' }
];
const FATForm = (props: any) => {
  const { form, data, selectUnit, FATOrTAF, setInitTable } = props;
  // 表格内容
  const [dataTable, setDataTable] = useState([]);
  // 档案类型列表
  const [ATList, setATList] = useState<IArchiveType[]>([]);
  // excel表头下拉框相关
  const [items, setItems] = useState([]);
  // 全宗列表
  const [fondsList, setFondsList] = useState([]);

  useEffect(() => {
    if (data) {
      setDataTable(data.initTable);
    }
  }, [data]);
  // 加载时获取全宗列表，获取成功后默认选中第一条并把第一条返回出去
  useEffect(() => {
    console.log(selectUnit, data);
    if (selectUnit) {
      fetchFondsListByUnitId(selectUnit).then((res) => {
        const _fondList: IFond[] = res.data;
        setFondsList(_fondList);
        if (data) {
          form.setFieldsValue({ description: data.description });
        } else {
          form.setFieldsValue({ description: _fondList[0].id });
        }
      });
    }
  }, [selectUnit]);
  const description = Form.useWatch('description', form);
  // 切换全宗自动加载档案类型
  useEffect(() => {
    if (description) {
      fetchATListByFondId(description).then((res) => {
        const _atList: IArchiveType[] = res.data;
        setATList(_atList);
        if (data) {
          form.setFieldsValue({ type: data.type });
        } else {
          form.setFieldsValue({ type: _atList[0]?.id });
        }
      });
    }
  }, [description]);
  const type = Form.useWatch('type', form);
  /* 获取字段列表 */
  useEffect(() => {
    if (ATList.length !== 0 && type) {
      const level = ATList.find((item) => item.id === type);
      console.log(level);
      const param = {
        archiveTypeId: level.id,
        atCode: level.atCode,
        atType: level.atType,
        level: [1]
      };
      searchFetchFields([{ ...param }]).then((res) => {
        const { data } = res;
        setItems(data);
      });
    }
  }, [type]);

  /**
   * @description: 清空全部数据
   */
  const clearAll = () => {
    const initData: any = {
      typeTitle: null,
      fieldName: null,
      title: null
    };
    setDataTable((state: any) => state.map((item: any) => ({ ...item, ...initData })));
  };

  const deleteItem = (key: string) => {
    setDataTable(delItemById(key, dataTable, 'key'));
  };
  /**
   * @description: 保存单元格操作选择的内容
   * @param {any} row
   */
  const handleSave = (row: any) => {
    const newData = jsonClone(dataTable);
    const index = newData.findIndex((item: any) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, { ...item, ...row });
    setDataTable(newData);
    setInitTable(newData);
  };

  return (
    <>
      <div className={cx('form-space')}>
        {FATOrTAF === 1 ? (
          <>
            <Space align="baseline" size={'small'}>
              <b>散文件</b>与
              <Form.Item name="description">
                <Select
                  style={{ width: 200 }}
                  options={fondsList.map((item) => ({ label: item.fondName, value: item.id }))}
                />
              </Form.Item>
              内
              <Form.Item name="type">
                <Select
                  style={{ width: 170 }}
                  options={ATList.map((item) => ({ label: item.atName, value: item.id }))}
                />
              </Form.Item>
              之间的“文件级”字段映射关系
            </Space>
          </>
        ) : (
          <>
            <Space align="baseline" size={'small'}>
              <Form.Item name="description">
                <Select
                  style={{ width: 200 }}
                  options={fondsList.map((item) => ({ label: item.fondName, value: item.id }))}
                />
              </Form.Item>
              内
              <Form.Item name="type">
                <Select
                  style={{ width: 170 }}
                  options={ATList.map((item) => ({ label: item.atName, value: item.id }))}
                />
              </Form.Item>
              之间的“文件级”字段与<b>散文件</b>映射关系
            </Space>
          </>
        )}
      </div>
      <Space direction={'vertical'} className={cx('space-form')}>
        <Space>
          <Button
            onClick={() => {
              setDataTable((state: any) => [...state, new ExcelItem(state.length)]);
            }}
          >
            添加一行
          </Button>
          <Button
            onClick={() => {
              clearAll();
            }}
          >
            删除
          </Button>
        </Space>
        <Table
          dataSource={dataTable}
          size="small"
          pagination={false}
          bordered
          // style={{ width: '100%' }}
        >
          <Column
            title="序号"
            key="idCol"
            align="center"
            render={(_val, _record, idx) => `${idx + 1}`}
          />
          {FATOrTAF === 1 ? (
            <Column
              title="散文件字段"
              dataIndex="title"
              key="title"
              align="center"
              render={(val, record: ILevel) => (
                <Select
                  value={val}
                  style={{ width: 200 }}
                  placeholder="请选择字段"
                  size="small"
                  onChange={(value) => {
                    handleSave({ ...record, title: value });
                  }}
                >
                  {items.map((item: any) => (
                    <Option key={item.field_name} value={item.field_desc}>
                      {item.field_desc}
                    </Option>
                  ))}
                </Select>
              )}
            />
          ) : (
            <Column
              title="档案类型字段"
              dataIndex="typeTitle"
              key="typeTitle"
              align="center"
              render={(val, record: any) => (
                <Select
                  value={val}
                  style={{ width: 140 }}
                  size="small"
                  placeholder="请选择字段"
                  onChange={(value) => {
                    handleSave({ ...record, typeTitle: value });
                  }}
                >
                  {items.map((item: any) => (
                    <Option key={item.field_name} value={item.field_desc}>
                      {item.field_desc}
                    </Option>
                  ))}
                </Select>
              )}
            />
          )}

          <Column
            title="关系"
            dataIndex="fieldName"
            key="fieldName"
            align="center"
            render={(val, record: any) => (
              <Select
                value={val}
                style={{ width: 140 }}
                size="small"
                placeholder="请选择字段"
                onChange={(value) => {
                  handleSave({ ...record, fieldName: value });
                }}
              >
                {relationship.map((item: any) => (
                  <Option key={item.id} value={item.id}>
                    {item.value}
                  </Option>
                ))}
              </Select>
            )}
          />
          {FATOrTAF === 2 ? (
            <Column
              title="散文件字段"
              dataIndex="title"
              key="title"
              align="center"
              render={(val, record: ILevel) => (
                <Select
                  value={val}
                  style={{ width: 200 }}
                  placeholder="请选择字段"
                  size="small"
                  onChange={(value) => {
                    handleSave({ ...record, title: value });
                  }}
                >
                  {items.map((item: any) => (
                    <Option key={item.field_name} value={item.field_desc}>
                      {item.field_desc}
                    </Option>
                  ))}
                </Select>
              )}
            />
          ) : (
            <Column
              title="档案类型字段"
              dataIndex="typeTitle"
              key="typeTitle"
              align="center"
              render={(val, record: any) => (
                <Select
                  value={val}
                  style={{ width: 140 }}
                  size="small"
                  placeholder="请选择字段"
                  onChange={(value) => {
                    handleSave({ ...record, typeTitle: value });
                  }}
                >
                  {items.map((item: any) => (
                    <Option key={item.field_name} value={item.field_desc}>
                      {item.field_desc}
                    </Option>
                  ))}
                </Select>
              )}
            />
          )}

          <Column
            title="操作"
            dataIndex="action"
            key="action"
            align="center"
            render={(_val, record: any) => (
              <Button
                type="link"
                size="small"
                danger
                onClick={() => {
                  deleteItem(record.key);
                }}
              >
                删除
              </Button>
            )}
          />
        </Table>
      </Space>
    </>
  );
};
export default memo(observer(FATForm));
